/**
 * 导航应用 - 主要功能实现
 */
class NavigationApp {
    constructor() {
        // 初始化应用
        this.init();
    }

    /**
     * 应用初始化
     */
    init() {
        // 初始化时钟
        this.initClock();
        
        // 初始化搜索引擎切换
        this.initSearchEngineSwitch();
        
        // 初始化搜索功能
        this.initSearch();
        
        // 初始化鼠标跟踪
        this.initMouseTracking();
        
        // 设置事件监听器
        this.setupEventListeners();
        
        // 加载统计数据
        this.loadStats();
        
        // 跟踪访问
        this.trackVisit();
    }

    /**
     * 初始化时钟
     */
    initClock() {
        // 简易农历算法（适合展示，准确率高，节气等特殊情况略有误差）
        function getLunarDate(date) {
            // 农历数据表（1900-2100年）
            const lunarInfo = [0x04bd8,0x04ae0,0x0a570,0x054d5,0x0d260,0x0d950,0x16554,0x056a0,0x09ad0,0x055d2,0x04ae0,0x0a5b6,0x0a4d0,0x0d250,0x1d255,0x0b540,0x0d6a0,0x0ada2,0x095b0,0x14977,0x04970,0x0a4b0,0x0b4b5,0x06a50,0x06d40,0x1ab54,0x02b60,0x09570,0x052f2,0x04970,0x06566,0x0d4a0,0x0ea50,0x06e95,0x05ad0,0x02b60,0x186e3,0x092e0,0x1c8d7,0x0c950,0x0d4a0,0x1d8a6,0x0b550,0x056a0,0x1a5b4,0x025d0,0x092d0,0x0d2b2,0x0a950,0x0b557,0x06ca0,0x0b550,0x15355,0x04da0,0x0a5d0,0x14573,0x052d0,0x0a9a8,0x0e950,0x06aa0,0x0aea6,0x0ab50,0x04b60,0x0aae4,0x0a570,0x05260,0x0f263,0x0d950,0x05b57,0x056a0,0x096d0,0x04dd5,0x04ad0,0x0a4d0,0x0d4d4,0x0d250,0x0d558,0x0b540,0x0b5a0,0x195a6,0x095b0,0x049b0,0x0a974,0x0a4b0,0x0b27a,0x06a50,0x06d40,0x0af46,0x0ab60,0x09570,0x04af5,0x04970,0x064b0,0x074a3,0x0ea50,0x06b58,0x05ac0,0x0ab60,0x096d5,0x092e0,0x0c960,0x0d954,0x0d4a0,0x0da50,0x07552,0x056a0,0x0abb7,0x025d0,0x092d0,0x0cab5,0x0a950,0x0b4a0,0x0baa4,0x0ad50,0x055d9,0x04ba0,0x0a5b0,0x15176,0x052b0,0x0a930,0x07954,0x06aa0,0x0ad50,0x05b52,0x04b60,0x0a6e6,0x0a4e0,0x0d260,0x0ea65,0x0d530,0x05aa0,0x076a3,0x096d0,0x04bd7,0x04ad0,0x0a4d0,0x1d0b6,0x0d250,0x0d520,0x0dd45,0x0b5a0,0x056d0,0x055b2,0x049b0,0x0a577,0x0a4b0,0x0aa50,0x1b255,0x06d20,0x0ada0];
            const solarMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
            const Animals = ["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"];
            const Gan = ["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"];
            const Zhi = ["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"];
            const nStr1 = ["日","一","二","三","四","五","六","七","八","九","十"];
            const nStr2 = ["初","十","廿","卅","" ];
            function lYearDays(y) {
                let i, sum = 348;
                for(i=0x8000; i>0x8; i>>=1) sum += (lunarInfo[y-1900] & i)? 1: 0;
                return(sum+leapDays(y));
            }
            function leapDays(y) {
                if(leapMonth(y))  return((lunarInfo[y-1900] & 0x10000)? 30: 29);
                else return(0);
            }
            function leapMonth(y) { return(lunarInfo[y-1900] & 0xf); }
            function monthDays(y,m) { return((lunarInfo[y-1900] & (0x10000>>m))? 30: 29); }
            function toGanZhi(year) {
                return Gan[(year-4)%10]+Zhi[(year-4)%12];
            }
            function getLunarDayString(day) {
                if(day===10) return "初十";
                if(day===20) return "二十";
                if(day===30) return "三十";
                return nStr2[Math.floor(day/10)] + nStr1[day%10];
            }
            let i, leap=0, temp=0;
            let baseDate = new Date(1900,0,31);
            let offset = Math.floor((date - baseDate)/86400000);
            let year, month, day;
            for(year=1900; year<2101 && offset>0; year++){
                temp = lYearDays(year);
                if(offset-temp<0) break;
                else offset -= temp;
            }
            if(offset<0){ offset+=temp; year--; }
            leap = leapMonth(year);
            let isLeap = false;
            for(month=1; month<13 && offset>0; month++){
                if(leap>0 && month==(leap+1) && !isLeap){ --month; isLeap=true; temp=leapDays(year); }
                else temp=monthDays(year,month);
                if(isLeap && month==(leap+1)) isLeap=false;
                offset -= temp;
            }
            if(offset<0){ offset+=temp; month--; }
            day = offset+1;
            let lunarMonthStr = (isLeap?"闰":"") + (month===1?"正":nStr1[month]) + "月";
            let lunarDayStr = getLunarDayString(day);
            return lunarMonthStr + lunarDayStr;
        }

        // 时间显示功能已移除，因为页面不需要这些元素
    }

    /**
     * 初始化分类导航 - 现在只是占位函数，因为使用全展示模式
     */
    initCategoryNavigation() {
        // 现在使用全展示模式，不需要分类切换功能
        // 直接初始化所有导航项目的鼠标跟踪
        setTimeout(() => {
            this.initMouseTracking();
        }, 100);
    }

    /**
     * 判断是否为闰年
     */
    isLeapYear(year) {
        return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
    }

    /**
     * 获取月份的天数
     */
    daysInMonth(year, month) {
        const days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        if (month === 2 && this.isLeapYear(year)) {
            return 29;
        }
        return days[month - 1];
    }



    /**
     * 初始化搜索引擎切换
     */
    initSearchEngineSwitch() {
        const currentEngine = document.getElementById('currentEngine');
        const engineDropdown = document.getElementById('engineDropdown');
        const engineIcon = document.getElementById('engineIcon');
        
        if (!currentEngine || !engineDropdown || !engineIcon) {
            console.warn('搜索引擎切换元素未找到');
            return;
        }
        
        // 加载保存的搜索引擎偏好，添加迁移逻辑
        let savedEngine = localStorage.getItem('preferredSearchEngine') || 'baidu';
        
        // 迁移逻辑：如果之前保存的是'google'，现在应该使用'bing'
        if (savedEngine === 'google') {
            savedEngine = 'bing';
            localStorage.setItem('preferredSearchEngine', 'bing');
        }
        
        // 标记当前激活的引擎选项
        const engineOptions = engineDropdown.querySelectorAll('.engine-option');
        engineOptions.forEach(option => {
            option.classList.toggle('active', option.dataset.engine === savedEngine);
        });
        
        // 切换到保存的搜索引擎
        this.switchSearchEngine(savedEngine);
        
        // 点击当前引擎显示/隐藏下拉菜单
        currentEngine.addEventListener('click', (e) => {
            e.stopPropagation();
            const searchEngineSelector = currentEngine.closest('.search-engine-selector');
            if (!searchEngineSelector) return;
            
            const isOpen = searchEngineSelector.classList.contains('open');
            
            if (isOpen) {
                searchEngineSelector.classList.remove('open');
            } else {
                searchEngineSelector.classList.add('open');
            }
        });
        
        // 点击引擎选项切换搜索引擎
        engineOptions.forEach(option => {
            option.addEventListener('click', (e) => {
                e.stopPropagation();
                const engine = option.dataset.engine;
                localStorage.setItem('preferredSearchEngine', engine);
                
                // 更新激活状态
                engineOptions.forEach(opt => opt.classList.remove('active'));
                option.classList.add('active');
                
                // 切换搜索引擎
                this.switchSearchEngine(engine);
                
                // 隐藏下拉菜单
                const searchEngineSelector = currentEngine.closest('.search-engine-selector');
                if (searchEngineSelector) {
                    searchEngineSelector.classList.remove('open');
                }
            });
        });
        
        // 点击页面其他地方关闭下拉菜单
        document.addEventListener('click', (e) => {
            const searchEngineSelector = currentEngine.closest('.search-engine-selector');
            if (!searchEngineSelector) return;
            
            // 确保点击的不是当前引擎或下拉菜单内的元素
            if (!currentEngine.contains(e.target) && !engineDropdown.contains(e.target)) {
                searchEngineSelector.classList.remove('open');
            }
        });
    }

    /**
     * 切换搜索引擎
     */
    switchSearchEngine(engine) {
        const searchForm = document.getElementById('searchForm');
        const searchInput = document.getElementById('searchInput');
        const engineIcon = document.getElementById('engineIcon');
        
        if (!searchForm || !searchInput || !engineIcon) return;
        
        // 不同搜索引擎的配置
        const engines = {
            baidu: {
                url: 'https://www.baidu.com/s',
                param: 'wd',
                text: 'B' // 百度图标文本
            },
            bing: {
                url: 'https://www.bing.com/search',
                param: 'q',
                text: 'W' // BING图标文本
            }
        };
        
        // 更新表单和图标
        if (engines[engine]) {
            searchForm.action = engines[engine].url;
            
            // 更新输入框的name属性
            if (searchInput.name !== engines[engine].param) {
                searchInput.name = engines[engine].param;
            }
            
            // 更新图标（文本内容）
            const textElement = engineIcon.querySelector('text');
            if (textElement) {
                textElement.textContent = engines[engine].text;
            }
        }
    }

    /**
     * 初始化搜索功能
     */
    initSearch() {
        const searchInput = document.getElementById('searchInput');
        const searchSuggestions = document.getElementById('searchSuggestions');
        const searchForm = document.getElementById('searchForm');
        
        if (!searchInput || !searchSuggestions || !searchForm) {
            console.warn('搜索元素未找到');
            return;
        }
        
        console.log('搜索功能初始化成功');
        
        // 输入事件监听 - 实时搜索建议
        // 创建防抖函数用于搜索建议调用
        const debouncedShowSuggestions = this.debounce((query) => {
            this.showSearchSuggestions(query);
        }, 300);
        
        searchInput.addEventListener('input', (e) => {
            const query = e.target.value.trim();
            
            if (query.length === 0) {
                this.hideSearchSuggestions();
                return;
            }
            
            // 使用防抖函数调用建议搜索
            debouncedShowSuggestions(query);
        });
        
        // 搜索表单提交 - 使用箭头函数保留this上下文
        searchForm.addEventListener('submit', (e) => {
            // 阻止默认提交，先执行统计
            e.preventDefault();
            
            const query = searchInput.value.trim();
            
            if (query) {
                console.log('提交搜索:', query);
                this.trackSearch(query).then(() => {
                    // 统计完成后手动提交表单
                    searchForm.submit();
                }).catch(() => {
                    // 即使统计失败也继续提交表单
                    searchForm.submit();
                });
            } else {
                // 如果查询为空，直接提交表单
                searchForm.submit();
            }
        });
        
        // 点击外部关闭建议
        document.addEventListener('click', (e) => {
            if (!searchInput.contains(e.target) && !searchSuggestions.contains(e.target)) {
                this.hideSearchSuggestions();
            }
        });
        
        // 搜索框获得焦点时的动画和行为
        searchInput.addEventListener('focus', () => {
            this.animateSearchBoxFocusImmediate(searchInput);
            // 点击搜索框时收起搜索建议列表
            this.hideSearchSuggestions();
        });
        
        searchInput.addEventListener('blur', () => {
            this.animateSearchBoxBlur(searchInput);
        });
    }

    /**
     * 显示搜索建议
     */
    async showSearchSuggestions(query) {
        const searchSuggestions = document.getElementById('searchSuggestions');
        
        if (!searchSuggestions) return;
        
        try {
            // 显示加载状态
            this.showSuggestionsLoading();
            
            // 获取搜索建议
            const suggestions = await this.getSearchSuggestions(query);
            
            // 如果没有建议或搜索框内容已变化，隐藏建议
            const searchInput = document.getElementById('searchInput');
            if (!suggestions.length || searchInput.value.trim() !== query) {
                this.hideSearchSuggestions();
                return;
            }
            
            // 生成建议HTML - 添加搜索图标
            let suggestionsHTML = '';
            suggestions.forEach(suggestion => {
                suggestionsHTML += `<div class="suggestion-item" data-query="${suggestion}">
                    <div class="suggestion-icon">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <circle cx="11" cy="11" r="8"></circle>
                            <path d="m21 21-4.35-4.35"></path>
                        </svg>
                    </div>
                    <div class="suggestion-text">
                        ${this.highlightQuery(suggestion, query)}
                    </div>
                </div>`;
            });
            
            // 更新建议列表
            searchSuggestions.innerHTML = suggestionsHTML;
            searchSuggestions.classList.add('show');
            
            // 设置建议项点击事件
            this.setupSuggestionClickEvents();
            this.setupSuggestionKeyboardNavigation();
            
        } catch (error) {
            console.error('获取搜索建议失败:', error);
            this.hideSearchSuggestions();
        }
    }

    /**
     * 显示建议加载状态
     */
    showSuggestionsLoading() {
        const searchSuggestions = document.getElementById('searchSuggestions');
        
        if (!searchSuggestions) return;
        
        // 显示加载动画和文本
        searchSuggestions.innerHTML = `
            <div class="suggestion-loading">
                <div class="loading-spinner"></div>
                <span class="loading-text">正在加载...</span>
            </div>
        `;
        searchSuggestions.classList.add('show');
    }

    /**
     * 获取搜索建议
     */
    async getSearchSuggestions(query) {
        if (!query || query.trim().length < 1) return [];
        
        const currentEngine = this.getCurrentSearchEngine();
        
        try {
            // 优先调用百度API获取实时建议
            return await this.getBaiduSuggestions(query.trim());
        } catch (error) {
            console.warn('获取搜索建议失败，使用本地建议:', error);
            // API失败时使用本地预设建议
            return this.getLocalSuggestions(query, currentEngine);
        }
    }
    
    /**
     * 通过百度API获取搜索建议
     */
    getBaiduSuggestions(query) {
        return new Promise((resolve, reject) => {
            // 设置3秒超时
            const timeoutId = setTimeout(() => {
                reject(new Error('获取百度建议超时'));
            }, 3000);
            
            // 创建唯一的回调函数名
            const callbackName = `baiduSuggestCallback_${Date.now()}`;
            
            // 创建script标签进行JSONP请求
            const scriptTag = document.createElement('script');
            
            // 定义全局回调函数
            window[callbackName] = (data) => {
                clearTimeout(timeoutId);
                try {
                    // 移除script标签
                    if (scriptTag && scriptTag.parentNode) {
                        scriptTag.parentNode.removeChild(scriptTag);
                    }
                    // 删除全局回调函数
                    delete window[callbackName];
                    
                    // 处理返回结果
                    if (data && data.s && Array.isArray(data.s)) {
                        // 过滤和处理建议结果
                        const suggestions = data.s
                            .filter(item => item && typeof item === 'string')
                            .slice(0, 8) // 限制数量
                            .map(item => item.trim())
                            .filter(item => item.length > 0);
                        resolve(suggestions);
                    } else {
                        resolve([]);
                    }
                } catch (error) {
                    reject(error);
                }
            };
            
            // 添加时间戳参数以避免缓存
            scriptTag.src = `https://suggestion.baidu.com/su?wd=${encodeURIComponent(query)}&p=3&cb=${callbackName}&t=${Date.now()}`;
            scriptTag.onerror = (error) => {
                clearTimeout(timeoutId);
                delete window[callbackName];
                if (scriptTag && scriptTag.parentNode) {
                    scriptTag.parentNode.removeChild(scriptTag);
                }
                reject(new Error('网络请求失败'));
            };
            
            document.head.appendChild(scriptTag);
        });
    }
    
    /**
     * 获取当前使用的搜索引擎
     */
    getCurrentSearchEngine() {
        const engineSelect = document.getElementById('searchEngine');
        return engineSelect ? engineSelect.value : 'baidu';
    }

    /**
     * 获取本地搜索建议
     */
    getLocalSuggestions(query, engine = 'baidu') {
        const suggestions = {
            baidu: [
                '编程教程', 'Vue.js', 'React', 'Python', 'JavaScript',
                '前端开发', '后端开发', '数据库', 'Git教程', 'Linux命令',
                '算法', '数据结构', 'Node.js', 'TypeScript', 'CSS动画',
                '机器学习', '人工智能', '深度学习', '区块链', '云计算',
                'HTML5', 'CSS3', 'Bootstrap', 'jQuery', 'Angular',
                'Docker', 'Kubernetes', 'Redis', 'MongoDB', 'MySQL'
            ],
            google: [
                'Programming tutorial', 'Vue.js guide', 'React documentation', 'Python examples', 'JavaScript MDN',
                'Frontend development', 'Backend development', 'Database tutorial', 'Git commands', 'Linux tutorial',
                'Algorithms', 'Data structures', 'Node.js guide', 'TypeScript handbook', 'CSS animations',
                'Machine learning', 'Artificial intelligence', 'Deep learning', 'Blockchain', 'Cloud computing',
                'HTML5 features', 'CSS3 tips', 'Bootstrap examples', 'jQuery tutorial', 'Angular documentation',
                'Docker commands', 'Kubernetes guide', 'Redis tutorial', 'MongoDB documentation', 'MySQL tutorial'
            ]
        };
        
        // 根据当前搜索引擎选择对应语言的建议，并过滤匹配项
        const engineSuggestions = suggestions[engine] || suggestions.baidu;
        return engineSuggestions
            .filter(item => item.toLowerCase().includes(query.toLowerCase()))
            .slice(0, 5);
    }

    /**
     * 高亮查询词
     */
    highlightQuery(text, query) {
        const regex = new RegExp(`(${query})`, 'gi');
        return text.replace(regex, '<strong>$1</strong>');
    }

    /**
     * 设置建议项点击事件
     */
    setupSuggestionClickEvents() {
        const searchInput = document.getElementById('searchInput');
        const searchForm = document.getElementById('searchForm');
        const suggestionItems = document.querySelectorAll('.suggestion-item');
        
        if (!searchInput || !searchForm || !suggestionItems.length) {
            console.warn('无法设置搜索建议点击事件：缺少必要元素');
            return;
        }
        
        suggestionItems.forEach(item => {
            // 为每个建议项添加点击事件
            const handleClick = () => {
                try {
                    // 获取查询词
                    const query = item.dataset.query;
                    
                    if (query && typeof query === 'string') {
                        // 设置搜索框值
                        searchInput.value = query;
                        
                        // 触发搜索框输入事件，确保界面更新
                        searchInput.dispatchEvent(new Event('input', { bubbles: true }));
                        
                        // 隐藏建议列表
                        this.hideSearchSuggestions();
                        
                        // 提交搜索表单
                        searchForm.submit();
                    }
                } catch (error) {
                    console.error('处理搜索建议点击失败:', error);
                    // 即使出错也隐藏建议列表
                    this.hideSearchSuggestions();
                }
            };
            
            // 添加点击事件监听器
            item.addEventListener('click', handleClick);
            
            // 添加鼠标悬停效果
            item.addEventListener('mouseenter', () => {
                // 移除其他项的高亮
                suggestionItems.forEach(suggestion => {
                    suggestion.classList.remove('highlighted');
                });
                // 高亮当前项
                item.classList.add('highlighted');
            });
            
            // 添加鼠标离开效果
            item.addEventListener('mouseleave', () => {
                item.classList.remove('highlighted');
            });
        });
    }

    /**
     * 设置建议键盘导航
     */
    setupSuggestionKeyboardNavigation() {
        const searchInput = document.getElementById('searchInput');
        const searchSuggestions = document.getElementById('searchSuggestions');
        const searchForm = document.getElementById('searchForm');
        const suggestionItems = document.querySelectorAll('.suggestion-item');
        
        if (!searchInput || !searchSuggestions || !searchForm || !suggestionItems.length) return;
        
        // 使用闭包保存currentIndex，确保每次调用都是独立的
        (function() {
            let currentIndex = -1;
            
            // 键盘事件处理函数
            const handleKeyDown = (e) => {
                // 只在建议显示时处理键盘事件
                if (!searchSuggestions.classList.contains('show')) {
                    // 移除事件监听器避免内存泄漏
                    searchInput.removeEventListener('keydown', handleKeyDown);
                    return;
                }
                
                switch (e.key) {
                    case 'ArrowDown':
                        e.preventDefault();
                        currentIndex = (currentIndex + 1) % suggestionItems.length;
                        this.updateHighlightedSuggestion(suggestionItems, currentIndex);
                        break;
                    case 'ArrowUp':
                        e.preventDefault();
                        currentIndex = (currentIndex - 1 + suggestionItems.length) % suggestionItems.length;
                        this.updateHighlightedSuggestion(suggestionItems, currentIndex);
                        break;
                    case 'Enter':
                        if (currentIndex >= 0 && currentIndex < suggestionItems.length) {
                            e.preventDefault();
                            suggestionItems[currentIndex].click();
                        }
                        break;
                    case 'Escape':
                        this.hideSearchSuggestions();
                        currentIndex = -1;
                        // 移除事件监听器避免内存泄漏
                        searchInput.removeEventListener('keydown', handleKeyDown);
                        break;
                }
            };
            
            // 添加键盘事件监听器
            searchInput.addEventListener('keydown', handleKeyDown);
        }).bind(this)();
    }

    /**
     * 更新高亮的建议项
     */
    updateHighlightedSuggestion(items, index) {
        items.forEach((item, i) => {
            item.classList.toggle('highlighted', i === index);
        });
        
        if (index >= 0 && index < items.length) {
            items[index].scrollIntoView({ block: 'nearest' });
        }
    }

    /**
     * 隐藏搜索建议
     */
    hideSearchSuggestions() {
        const searchSuggestions = document.getElementById('searchSuggestions');
        
        if (!searchSuggestions) return;
        
        searchSuggestions.classList.remove('show');
    }

    /**
     * 立即聚焦搜索框的动画
     */
    animateSearchBoxFocusImmediate(element) {
        if (!element) return;
        
        // 直接设置样式，避免动画延迟
        this.setImmediateBorderRadius(element, '8px');
        
        // 添加其他聚焦样式
        element.style.boxShadow = '0 0 0 2px rgba(0, 123, 255, 0.25)';
    }

    /**
     * 立即设置圆角
     */
    setImmediateBorderRadius(element, radius) {
        if (!element) return;
        
        // 直接设置圆角
        element.style.borderRadius = radius;
    }
    
    /**
     * 防抖函数
     * 用于延迟执行函数，避免频繁触发
     */
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    /**
     * 搜索框失焦动画
     */
    animateSearchBoxBlur(element) {
        if (!element) return;
        
        // 直接设置回默认样式
        element.style.borderRadius = '';
        element.style.boxShadow = '';
    }

    /**
     * 解析CSS值，包括CSS变量
     */
    resolveCSSValue(element, value) {
        if (!value.includes('var(')) {
            return value;
        }
        
        // 创建临时元素来解析CSS变量
        const tempDiv = document.createElement('div');
        tempDiv.style.borderRadius = value;
        document.body.appendChild(tempDiv);
        const computedValue = getComputedStyle(tempDiv).borderRadius;
        document.body.removeChild(tempDiv);
        
        return computedValue || value;
    }

    /**
     * 初始化鼠标跟踪（用于卡片悬停效果）
     */
    initMouseTracking() {
        const navCards = document.querySelectorAll('.nav-link');
        
        navCards.forEach(card => {
            card.addEventListener('mousemove', (e) => {
                const rect = card.getBoundingClientRect();
                const x = e.clientX - rect.left;
                const y = e.clientY - rect.top;
                
                card.style.setProperty('--mouse-x', `${x}px`);
                card.style.setProperty('--mouse-y', `${y}px`);
            });
        });
    }

    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 导航卡片点击统计（包括常用导航和普通导航）
        document.addEventListener('click', (e) => {
            // 优先检查常用导航项
            const favoriteNavItem = e.target.closest('.favorite-nav-item');
            if (favoriteNavItem) {
                const navId = favoriteNavItem.dataset.navId;
                if (navId) {
                    this.trackNavClick(navId);
                }
                return;
            }
            
            // 检查普通导航卡片
            const navCard = e.target.closest('.nav-link');
            if (navCard) {
                const navId = navCard.dataset.navId;
                if (navId) {
                    this.trackNavClick(navId);
                }
            }
        });
        
        // 页面可见性变化
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden) {
                this.loadStats();
            }
        });
        
        // 窗口大小变化
        window.addEventListener('resize', this.debounce(() => {
            this.initMouseTracking();
        }, 250));
        
        // 滚动优化
        let scrollTimer = null;
        window.addEventListener('scroll', () => {
            if (scrollTimer) return;
            
            scrollTimer = setTimeout(() => {
                scrollTimer = null;
                // 可以在这里添加滚动相关的优化
            }, 100);
        });
    }

    /**
     * 跟踪搜索
     */
    async trackSearch(query) {
        if (!query || !query.trim()) {
            console.warn('搜索查询为空，不进行统计');
            return;
        }
        
        const trimmedQuery = query.trim();
        console.log('跟踪搜索:', trimmedQuery);
        
        // 获取当前选择的搜索引擎
        const savedEngine = localStorage.getItem('preferredSearchEngine') || 'baidu';
        console.log('当前搜索引擎:', savedEngine);
        
        try {
            // 使用config.js中提供的方法获取正确的API URL
            const url = window.CONFIG?.getApiUrl ? 
                window.CONFIG.getApiUrl('stats') : 
                '/api/stats';
            
            console.log('API URL:', url);
            
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'track_search',
                    query: trimmedQuery,
                    engine: savedEngine // 添加搜索引擎信息
                })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
            }
            
            const result = await response.json();
            if (!result.success) {
                console.warn('搜索统计失败:', result.message);
            } else {
                console.log('搜索统计成功:', result);
            }
            
            return result;
        } catch (error) {
            console.error('搜索统计错误:', error);
            
            // 备用方案：尝试使用简单的GET请求
            try {
                const params = { 
                    action: 'track_search', 
                    query: trimmedQuery,
                    engine: savedEngine // 添加搜索引擎信息
                };
                const url = window.CONFIG?.getApiUrl ? 
                    window.CONFIG.getApiUrl('stats', params) : 
                    `/api/stats?action=track_search&query=${encodeURIComponent(trimmedQuery)}&engine=${encodeURIComponent(savedEngine)}`;
                
                console.log('备用API URL:', url);
                await fetch(url, { method: 'GET' });
                console.log('搜索统计备用方案执行');
                return { success: true, message: '备用方案执行成功' };
            } catch (backupError) {
                console.error('搜索统计备用方案也失败:', backupError);
                return { success: false, message: '所有方案均失败' };
            }
        }
    }

    /**
     * 跟踪导航点击
     */
    async trackNavClick(navId) {
        if (!navId) return;
        
        try {
            const response = await fetch(`${window.CONFIG.apiUrl}stats`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'track_click',
                    nav_id: parseInt(navId)
                })
            });
            
            const result = await response.json();
            if (!result.success) {
                console.warn('点击统计失败:', result.message);
            }
        } catch (error) {
            console.error('点击统计错误:', error);
        }
    }

    /**
     * 跟踪页面访问
     */
    async trackVisit() {
        // 使用智能的重复统计防护机制
        const now = Date.now();
        const lastVisitKey = 'lastVisitTracked';
        
        try {
            // 标记访问统计开始（设置当前时间戳）
            localStorage.setItem(lastVisitKey, now.toString());
            
            // 增加重试机制
            let retryCount = 0;
            const maxRetries = 3;
            
            while (retryCount < maxRetries) {
                try {
                    const controller = new AbortController();
                    const timeoutId = setTimeout(() => controller.abort(), 5000);
                    
                    // 发送访问统计请求
                    const response = await fetch(`${window.CONFIG.apiUrl}stats`, {
                        method: 'POST',
                        headers: { 
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({ action: 'increment_visit' }),
                        signal: controller.signal,
                        cache: 'no-cache'
                    });
                    
                    clearTimeout(timeoutId);
                    
                    if (response.ok) {
                        const result = await response.json();
                        if (result.success) {
                            // 成功后立即更新本地显示
                            this.loadStats();
                            return;
                        }
                    }
                } catch (fetchError) {
                    if (retryCount < maxRetries - 1) {
                        // 等待一段时间后重试
                        await new Promise(resolve => setTimeout(resolve, 1000 * (retryCount + 1)));
                    }
                }
                
                retryCount++;
            }
            
            // 失败时清除标记，允许下次重试
            localStorage.removeItem(lastVisitKey);
            
        } catch (error) {
            console.error('访问统计严重错误:', error);
            // 失败时清除标记，允许下次重试
            localStorage.removeItem(lastVisitKey);
        }
    }

    /**
     * 加载统计数据
     */
    async loadStats() {
        try {
            const response = await fetch(`${window.CONFIG.apiUrl}stats`);
            const stats = await response.json();
            
            if (stats.success && stats.data) {
                this.updateStats(stats.data);
            }
        } catch (error) {
            console.error('加载统计数据失败:', error);
        }
    }

    /**
     * 更新统计显示
     */
    updateStats(stats) {
        this.updateElement('totalVisits', this.formatNumber(stats.total_visits || 0));
        this.updateElement('todayVisits', this.formatNumber(stats.today_visits || 0));
    }

    /**
     * 格式化数字
     */
    formatNumber(num) {
        // 直接返回完整数字，使用千分位分隔符
        return num.toLocaleString();
    }

    /**
     * 更新元素内容
     */
    updateElement(id, content) {
        const element = document.getElementById(id);
        if (element) {
            // 确保内容被正确更新，无论当前内容是什么
            element.textContent = content;
        } else {
            console.warn(`元素ID '${id}' 未找到`);
        }
    }

    /**
     * 处理页面加载完成后的初始化
     */
    initializeAfterLoad() {
        // 页面完全加载完成后执行的操作
        // 这里可以添加一些需要等待所有资源加载完成的初始化操作
    }

    /**
     * 防抖函数
     */
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    // 初始化应用
    window.navApp = new NavigationApp();
    
    // 页面完全加载完成事件监听器
    window.addEventListener('load', () => {
        // 注意：访问统计已在初始化时调用，此处不再重复调用
    });
    
    // 性能监控
    if ('performance' in window) {
        window.addEventListener('load', () => {
            const perfData = performance.timing;
            const loadTime = perfData.loadEventEnd - perfData.navigationStart;
            
            if (loadTime > 0) {
                console.log(`页面加载时间: ${loadTime}ms`);
            }
        });
    }
    
    // 错误监控
    window.addEventListener('error', (e) => {
        console.error('JavaScript错误:', e.error);
    });
    
    // Service Worker 注册（可选）
    if ('serviceWorker' in navigator) {
        // 可以在这里注册 Service Worker 实现离线功能
    }
});

// 导出给全局使用
window.NavigationApp = NavigationApp;
